<script setup>
import { useRouter } from 'vue-router'
import { ref } from 'vue'
import navbar from './navbar.vue'
import api from '@/api'
import { transformDuration } from '@/utils'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh'
import { showNotify } from 'vant'

dayjs.locale('zh')
dayjs.extend(relativeTime)

const $router = useRouter()
const videos = ref([])
const page = ref(1)
const total = ref(0)
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)

const keyword = ref('')
const showAction = ref(false)
const actions = ref([])
const actions0 = ref([
  { name: '视频详情' },
  { name: '播放原视频' },
  { name: '下载原视频' },
  { name: '提交剪辑' }, // 0
  { name: '删除视频' },
])
const actions1 = ref([
  { name: '视频详情' },
  { name: '播放原视频' },
  { name: '下载原视频' },
  { name: '删除视频' },
])
const actions2 = ref([
  { name: '视频详情' },
  { name: '播放原视频' },
  { name: '下载原视频' },
  { name: '播放剪辑视频' }, // 2
  { name: '下载剪辑视频' }, // 2
  { name: '删除视频' },
])

const currentVideo = ref({})
const formShow = ref(false)
const fileList = ref([])
const form = ref({
  image: '',
  clip_need: '',
})

const afterRead = async (file) => {
  const formData = new FormData();
  formData.append('file', file.file);
  const res = await api.post('upload', formData)
  console.log('res',res)
  fileList.value = [{
    url: res.url
  }]
}

const beforeClose = (action) => {
  console.warn('action',action)
  new Promise((resolve) => {
    resolve(action === 'cancel');
  });
}

const formConfirm = async () => {
  // if(!fileList.value.length) {
  //   showNotify({ type: 'danger', message: '请上传背景图片' })
  //   return false
  // }
  // if(!form.value.clip_need) {
  //   showNotify({ type: 'danger', message: '剪辑需求不可为空' })
  //   return false
  // }
  // form.value.image = fileList.value.map((e)=> e = e.url).toString()
  // console.log('form.value.image',form.value.image)
  try {
    const res = await api.post('ip/subClip', {
      video_id: currentVideo.value.id,
      image: form.value.image,
      clip_need: form.value.clip_need,
    })
    showNotify({ type: 'success', message: res.message })
    // formShow.value = false
    getVideos()
  } catch (error) {
    console.error(error)
  }
}

const formCancel = async () => {
  formShow.value = false
}

const getVideos = async () => {
  loading.value = true
  page.value = 1
  finished.value = false
  videos.value = []
  total.value = 0
  try {
    const resp = await api.get('ip/videos', {
      params: {
        keyword: keyword.value
      },
    })
    videos.value = resp.data
    total.value = resp.total
    if (videos.value.length == resp.total) {
      finished.value = true
    }
  } catch (error) {
    console.error(error)
  }
  loading.value = false
  refreshing.value = false
}

const onLoad = async () => {
  if (!finished.value) {
    try {
      page.value += 1
      const resp = await api.get('ip/videos', { params: { page: page.value } })
      if (resp.data.length) {
        videos.value.push(...resp.data)
        total.value = resp.total
      } else {
        finished.value = true
      }
    } catch (error) {
      console.error(error)
    }
  }
  loading.value = false
}

const onRefresh = async () => {
  getVideos()
}

const show = (item) => {
  // window.location.href = item.url
  currentVideo.value = item
  var action = []
  if(item.status==0) {
    action = actions0.value
  }else if(item.status==1) {
    action = actions1.value
  }else if(item.status==2) {
    action = actions2.value
  }
  
  actions.value = action

  showAction.value = true
}

const onSelect = async(item) => {
  
  switch (item.name) {
    case '视频详情':
      $router.push('/ip/videoDetails?id=' + currentVideo.value.id)
      break;
    case '播放原视频':
      $router.push('/ip/viewVideo?url=' + currentVideo.value.url)
      break;
    case '下载原视频':
      window.open(currentVideo.value.url)
      // let a = document.createElement('a')
      // a.download = 'test.mp4'
      // a.href = currentVideo.value.url
      // a.click();
      break;
    case '提交剪辑':
    formShow.value = true
      break;
    case '播放剪辑视频':
    $router.push('/ip/viewVideo?url=' + currentVideo.value.clip_url)
      break;
    case '下载剪辑视频':
    window.open(currentVideo.value.clip_url)
      break;
    case '删除视频':
      showConfirmDialog({
        title: '提示',
        message:
          '确认删除该视频吗？',
        })
          .then(() => {
            console.log('确认')
            delVideo()
          })
          .catch(() => {
            console.log('取消')
          });
      break;
  }
}

const onCancel = async(item) => {
  showAction.value = false
}

const delVideo = async() => {
  try {
    const res = await api.get('ip/delVideo', {
      params: {
        video_id: currentVideo.value.id
      },
    })
    showNotify({ type: 'success', message: res.message })
    getVideos()
  } catch (error) {
    console.error(error)
  }
}

const backgroundList = ref([])

const getBackgroundList = async () => {
  try {
    const res = await api.get('ip/backgroundList')
    backgroundList.value = res.data
  } catch (error) {
    console.error(error)
  }
}

const viewImg = async (url) => {
  showImagePreview([url]);
}

getVideos()
getBackgroundList()
</script>

<template>
  <div class="container">
    <div class="flex at_c bb pr12">
      <div class="w100">
        <van-search
          v-model="keyword"
          placeholder="请输入关键词搜索视频"
          @search="getVideos"
        />
      </div>
      <van-button square class="fs_0" @click="getVideos" type="primary" size="small">搜索</van-button>
      <!-- <van-button square class="fs_0" type="primary" size="small">上传视频</van-button> -->
    </div>

    <van-pull-refresh class="list" v-model="refreshing" @refresh="onRefresh">
      <van-list v-model:loading="loading" :finished="finished" :finished-text="videos.length && !loading ? '没有更多了' : '暂无素材'" @load="onLoad">
        <div class="materials">
          <div class="material" v-for="(item,index) in videos" @click="show(item)" :key="index">
            <div class="body">
              <div class="title">{{ item.material.title }}</div>
              <div class="status_label blue" v-if="item.status==0">待剪辑</div>
              <div class="status_label orange" v-if="item.status==1">待生成剪辑后视频</div>
              <div class="status_label red" v-if="item.status==2">完成</div>
              <div class="content">{{ item.material.content }}</div>
              <div class="footer">
                <div class="category-name">{{ item.material.category.name }}</div>

                <div class="count">
                  <van-icon name="clock-o" style="margin-right: 5px" />
                  {{ transformDuration(item.times) }}
                </div>

                <div class="count">{{ dayjs(item.created_at).fromNow() }}</div>
              </div>
              <!-- <div class="createtime">{{ item.submit_time }}</div> -->
            </div>
            <div class="image">
              <img :src="item.material.image" />
            </div>
          </div>
        </div>
      </van-list>
    </van-pull-refresh>

    <van-action-sheet v-model:show="showAction" :actions="actions" @select="onSelect" cancel-text="取消" close-on-click-action @cancel="onCancel" />

    <van-dialog v-model:show="formShow" title="提交剪辑" show-cancel-button @confirm="formConfirm" @cancel="formCancel" @beforeClose="beforeClose" >
      <div>
        <van-cell-group>
          <van-cell class="ces" title="背景图片">
            <div class="cover_imgs">
              <van-radio-group v-model="form.image">
                <van-radio v-for="(item,index) in backgroundList" :key="index" :name="item.image">
                  <img @click="viewImg(item.image)" class="cover_img" :src="item.image" alt="">
                </van-radio>
              </van-radio-group>
            </div>
            <!-- <van-uploader  max-count="1" v-model="fileList" :after-read="afterRead" /> -->
          </van-cell>

          <van-field
            type="textarea"
            v-model="form.clip_need"
            label="剪辑需求"
            placeholder="请输入剪辑需求"
            rows="1"
            autosize
          />
        </van-cell-group>
      </div>
    </van-dialog>

    <navbar></navbar>
  </div>
</template>

<style lang="scss" scoped>
.container {
  height: 100vh;
  overflow: auto;
  padding-bottom: 16vw;
}

.w100 {
  width: 100%;
}

.flex {
  display: flex;
}

.at_c {
  align-items: center;
}

.fs_0 {
  flex-shrink: 0;
  margin-left: 5px;
}

.bb {
  box-sizing: border-box;
}

.pr12 {
  padding-right: 12px;
}

.status_label {
  font-size: 12px;
  border: 1px solid;
  display: inline;
  box-sizing: border-box;
  padding: 1px 2px;
  border-radius: 3px;
}

.blue {
  color: #0e63fe;
  border-color: #0e63fe;
}

.orange {
  color: orange;
  border-color: orange;
}

.red {
  color: red;
  border-color: red;
}

.createtime {
  margin-top: 10px;
  font-size: 12px;
  color: #9c9b9b;
}

.ces {
  display: flex;
  align-items: center;
}

.cover_imgs {
  width: 100%;
  max-height: 100px;
  overflow-y: auto;
}

.cover_img {
  width: 80px;
  height: 60px;
  display: block;
  object-fit: cover;
  margin-bottom: 10px;
}
</style>
<style scoped>
/deep/ .van-cell__value {
  text-align: left;
}
</style>